package org.yanghe.controller;

import com.netflix.hystrix.contrib.javanica.annotation.HystrixCommand;
import com.netflix.hystrix.contrib.javanica.annotation.HystrixProperty;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RestController;


/**
 * 服务熔断
 */
@RestController
public class CHystrixCircuitBreakerController {

    //整体解释：在十秒中，有十次请求，请求错误率达到 60% 跳闸
    @HystrixCommand(fallbackMethod = "providerCircuitBreaker_FallBack",commandProperties = {
            //是否开启断路器
            @HystrixProperty(name = "circuitBreaker.enabled",value = "true"),
            //请求次数
            @HystrixProperty(name = "circuitBreaker.requestVolumeThreshold",value = "10"),
            //时间窗口期（时间范围）
            @HystrixProperty(name = "circuitBreaker.sleepWindowInMilliseconds",value = "10000"),
            //失败率达到多少后跳闸
            @HystrixProperty(name = "circuitBreaker.errorThresholdPercentage",value = "60")
    })
    @GetMapping("/provider/circuitbreaker/{id}")
    public String providerCircuitBreaker(@PathVariable("id")Integer id){
        if(id<0){
            throw new RuntimeException("********id 不能为负数");
        }
        String serialNumber=String.valueOf(System.currentTimeMillis());

        return "调用成功，流水号："+serialNumber+" 线程号："+Thread.currentThread().getName();
    }

    public String providerCircuitBreaker_FallBack(@PathVariable("id")Integer id){
        return "调用失败，id 不能为负数，当前 id :"+id;
    }
}
